package com.cqq.login.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqq.auth.service.OrganizationService;
import com.cqq.auth.service.UserService;
import com.cqq.auth.service.bean.OrganizationBean;
import com.cqq.auth.service.bean.OrganizationQueryBean;
import com.cqq.auth.service.bean.UserBean;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.MessageBean;
import com.cqq.common.core.util.MapBuilder;
import com.cqq.login.bean.UserView;

@Controller
@RequestMapping("usersAndOrgs")
/**
 * <h3>选择用户与组织</h3>
 * 
 * @author CHENQQ
 * @datet 2015-08-05
 */
public class UsersAndOrgsController extends BaseController {

	@Resource
	private UserService userService;
	@Resource
	private OrganizationService organizationService;

	//private static Integer SUPER_ORG_ID = 1;//顶级组织id
	
	/**
	 * 查询顶级组织
	 * 
	 * @param request
	 * @param response
	 * @param out
	 * @return
	 */
	@RequestMapping("queryOrgs")
	@ResponseBody
	public MessageBean queryOrgs(HttpServletRequest request) {
		try {
			String orgIdStr = request.getParameter("superorgid");
			if(orgIdStr==null||orgIdStr.trim().length()<=0){
				return super.buildMessage(MESSAGE_TYPE_ERROR, "查询组织失败");
			}
			OrganizationQueryBean queryBean = new OrganizationQueryBean();
			queryBean.setId(Integer.parseInt(orgIdStr));
			//queryBean.setOrderBy("id asc");
			List<OrganizationBean> listorganizations = organizationService.queryOrgByParentId(queryBean);//顶级组织
			return super.buildMessage(MESSAGE_TYPE_SUCCESS, "成功",listorganizations);
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, "查询组织失败");
		}
	}
	
	/**
	 * 查询子组织与子用户
	 * 
	 * @param request
	 * @param response
	 * @param out
	 * @return
	 */
	@RequestMapping("queryUsersAndOrgsByOrgId")
	@ResponseBody
	public MessageBean queryUsersAndOrgsByOrgId(HttpServletRequest request) {
		try{
			List<OrganizationBean> listorganizations = null ;
			List<UserView> listUserViews = null ;
			if(request.getParameter("orgid")!=null){
				Integer orgid = Integer.parseInt(request.getParameter("orgid"));//组织Id
				String userIds = request.getParameter("userIds");//准备分发/补发的用户
				String receivedIds = request.getParameter("receivedIds");//已经分发/补发的用户
				OrganizationQueryBean queryBean = new OrganizationQueryBean();
				queryBean.setId(orgid);
				//queryBean.setOrderBy("id asc");
				listorganizations = organizationService.queryOrgByParentId(queryBean);//当前组织下第一层子组织
				List<UserBean> listUserBeans = userService.listUserByOrgIdAndStatus(new Integer[]{orgid},1);//当前组织下所对应的用户,状态启用（1）的用户
				if(listUserBeans!=null&&listUserBeans.size()>0){
					listUserViews = new ArrayList<UserView>();
					for (UserBean bean : listUserBeans) {
						if(isExist(bean.getId().toString(),receivedIds))
							continue;
						UserView view = new UserView();
						BeanUtils.copyProperties(bean, view);
						if(isChecked(bean.getId().toString(),userIds))
							view.setIsChecked(UserView.CHECKED);
						listUserViews.add(view);
					}
				}
				Map<String, Object> build = MapBuilder.putObj("listorganizations", (listorganizations!=null&&listorganizations.size()>0)?listorganizations:"null")
						.and("userList", (listUserViews!=null&&listUserViews.size()>0)?listUserViews:"null").build();
				
				return super.buildMessage(MESSAGE_TYPE_SUCCESS, "成功",build);
			}else{
				return super.buildMessage(MESSAGE_TYPE_ERROR, "父组织对象为空");
			}
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, "查询组织失败");
		}
	}
	
	
	/**
	 * 根据部门名称查询子组织，用户名称查询子用户
	 * 
	 * @param request
	 * @param response
	 * @param out
	 * @return
	 */
	@RequestMapping("queryUsersAndOrgsByKeyword")
	@ResponseBody
	public MessageBean queryUsersAndOrgsByKeyword(HttpServletRequest request,
			HttpServletResponse response) {
		try{
			List<OrganizationBean> listorganizations = null ;
			List<UserView> listUserViews = null ;
			String orgIdStr = request.getParameter("superorgid");
			if(orgIdStr==null||orgIdStr.trim().length()<=0){
				return super.buildMessage(MESSAGE_TYPE_ERROR, "查询组织失败");
			}
			String userNameOrOrgName = request.getParameter("userNameOrOrgName");
			String userIds = request.getParameter("userIds");//准备分发/补发的用户
			String receivedIds = request.getParameter("receivedIds");//已经分发/补发的用户
			Map<String, Object> build = new HashMap<String, Object>();
			if(userNameOrOrgName!=null){
				listorganizations = organizationService.listChildrenOrgByName(userNameOrOrgName,Integer.parseInt(orgIdStr));//当前组织下第一层子组织
				List<UserBean> listUserBeans = userService.queryUserByParentOrgIdandStatus(Integer.parseInt(orgIdStr),userNameOrOrgName,1);//当前组织下所对应的用户,状态启用（1）的用户
				if(listUserBeans!=null&&listUserBeans.size()>0){
					listUserViews = new ArrayList<UserView>();
					for (UserBean bean : listUserBeans) {
						if(isExist(bean.getId().toString(),receivedIds))
							continue;
						UserView view = new UserView();
						BeanUtils.copyProperties(bean, view);
						if(isChecked(bean.getId().toString(),userIds))
							view.setIsChecked(UserView.CHECKED);
						listUserViews.add(view);
					}
				}
				build.put("userList", listUserViews);
			}else{
				listorganizations = organizationService.listOrganizationByParentId(Integer.parseInt(orgIdStr));//顶级组织
				build.put("userList", "null");
				
			}
			build.put("listorganizations", (listorganizations!=null&&listorganizations.size()>0)?listorganizations:"null");
			return super.buildMessage(MESSAGE_TYPE_SUCCESS, "成功",build);
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			return super.buildMessage(MESSAGE_TYPE_ERROR, "查询组织失败");
		}
	}
	
	private boolean isExist(String id,String receivedIds){
		if(receivedIds==null||receivedIds.trim().length()<=0)
			return false;
		String[] userIds = receivedIds.split(",");
		if(userIds.length<=0)
			return false;
		for (String userId : userIds) {
			if(id.equals(userId))
				return true;
		}
		return false;
	}
	
	private boolean isChecked(String id,String userIdsStr){
		if(userIdsStr==null||userIdsStr.trim().length()<=0)
			return false;
		String[] userIds = userIdsStr.split(",");
		if(userIds.length<=0)
			return false;
		for (String userId : userIds) {
			if(id.equals(userId))
				return true;
		}
		return false;
	}
	
}
